<?php
/**
 * Created by PhpStorm.
 * User: xuke
 * Date: 16/6/21
 * Time: 下午2:52
 */

namespace App\Logic;

use App\Http\Model\Order AS OrderModel;
use App\Exceptions\ApiException;
use App\Http\Model\GoodsSku AS GoodsSkuModel;
use App\Http\Model\OrderSub AS OrderSubModel;
use App\Http\Model\OrderGoods AS OrderGoodsModel;
use App\Http\Model\Provider AS ProviderModel;

class OrderLogic extends BaseLogic
{
    protected $_order = null;
    /** @var null collection */
    protected $_orderGoods = null;
    protected $_order_sub = null; //子订单
    protected $_orderProviderGoods = null;

    public function __construct($order)
    {
        $this->_order = $order;
    }


    public static function initByOrder($order_id)
    {
        $order = OrderModel::where('order_id', $order_id)->first();
        if (emtpy($order))
        {
            throw new ApiException(-2, '订单不存在');
        }
        return new static($order);
    }

    public static function create()
    {
        $order = new OrderModel();
        return new static($order);
    }

    public function setUser($user_id)
    {
        $this->_order->setUser($user_id);
        return $this;
    }

    /**设置订单商品列表
     * @param $sku array
     */
    public function setSkus($skuList)
    {
        $skuIds = array_column($skuList, 'sku_id');
        $skuGoodsList = GoodsSkuModel::whereIn('sku_id', $skuIds)->get()->keyBy('sku_id');
        foreach ($skuList as $sku)
        {

            $this->setSku($skuGoodsList->get($sku['sku_id']), $sku['num']);
        }
        return $this;
    }

    /**设置订单商品sku
     * @param $sku int|GoodsSkuModel
     */
    public function setSku($sku, $num)
    {
        if (is_numeric($sku))
        {
            $sku = GoodsSkuModel::find($sku);
            if (empty($sku))
            {
                throw new ApiException('未找到商品sku信息', -2);
            }
        }
        if (!$sku instanceof GoodsSkuModel)
        {
            throw new ApiException('sku商品信息错误', -2);
        }
        $sku->load('goods');


        $key = $sku->sku_id.'_';
        if ($this->getOrderGoods()->has($key))
        {
            $this->setOrderGoods($sku, $num);
        }else{
            $this->addOrderGoods($sku, $num);
        }
        
    }


    /**添加订单商品
     * @param $sku
     * @param $num
     */
    public function addOrderGoods($sku, $num)
    {
        $orderGoods = new OrderGoodsModel();
        $orderGoods->setGoods($sku);
        $orderGoods->setNum($num);
        $key = $sku->sku_id."_";
//        collect($this->_orderGoods)->put($key,$orderGoods);
        $this->_orderGoods[] = $orderGoods;

        return $this;
    }

    /**设置订单商品
     * @param $sku
     * @param $num
     */
    public function setOrderGoods($sku, $num)
    {
        $key = $sku->sku_id.'_';
        $orderGoods = $this->getOrderGoods()->get($key);
        $orderGoods->setNum($num);
        return $this;
    }

    /**设置订单原始价格和商品总数量
     * @return $this
     */
    public function setOrderNumAndPrice()
    {
        $origin_price = 0;
        $totalNum = 0;
        foreach ($this->getOrderGoods() as $orderGoods)
        {
            $origin_price += $orderGoods->origin_price;
            $totalNum += $orderGoods->goods_num;
        }
        $this->getOrder()->goods_price = $origin_price;
        $this->getOrder()->goods_num = $totalNum;
        return $this;
    }

    /**
     * 设置订单号
     */
    public function setOrderSn()
    {
        $this->getOrder()->setOrderSn();
        return $this;
    }

    public function setOrder()
    {

    }

    public function getOrder()
    {
        return $this->_order;
    }

    public function getOrderGoods()
    {
        return collect($this->_orderGoods)->keyBy(function($item){
            return $item->sku_id."_".$item->bundle_id;
        });
    }

    public function setOrderAddress($address)
    {
        $this->getOrder()->express_address = $address->express_address;
        $this->getOrder()->express_name = $address->express_name;
        $this->getOrder()->express_mobile = $address->express_mobile;
        return $this;
    }

    public function getOrderSub($refresh=false)
    {

        return collect($this->_order_sub)->keyBy('provider_id');
    }

    public function getOrderProviderGoods()
    {
        return collect($this->_orderProviderGoods);
    }

    private function setOrderSubList()
    {
        $orderProviderGoods = $this->getOrderGoods()->groupBy('provider_id');
        foreach ($orderProviderGoods as $provider_id => $providerGoods)
        {
            if (!$this->getOrderSub()->get($provider_id))
            {
                $orderSubModel = new OrderSubModel();
                $providerModel = ProviderModel::find($provider_id);
                if (!$providerModel)
                {
                    throw new ApiException(-2, '供应商信息不存在');
                }
                $orderSubModel->setOrder($this->getOrder())->setProvider($providerModel);
//                $this->_orderProviderGoods->put($providerGoods->provider_id, $orderSubModel);
                $this->_order_sub[] = $orderSubModel;
            }
        }
        return $this;
    }

    /**
     * 设置订单商品的子订单号
     */
    private function setOrderGoodsOrderSub()
    {
        $orderSubList = $this->getOrderSub()->keyBy('provider_id');
        $orderGoodsList = $this->getOrderGoods()->groupBy('provider_id');
        foreach ($orderSubList as $key => $orderSub)
        {
            foreach ($orderGoodsList[$key] as $orderGoods)
            {
                $orderGoods->setOrderSubId($orderSub->order_sub_id);
            }
        }
        return $this;
    }


    private function saveOrderSub()
    {
        $this->getOrder()->subOrder()->saveMany($this->getOrderSub());
        return $this;
    }


    public function saveOrderGoods()
    {
        $this->getOrder()->orderGoods()->saveMany($this->getOrderGoods());
        return $this;
    }


    public function saveOrder()
    {
        $this->getOrder()->save();
        $this->setOrderSubList()->saveOrderSub();
        $this->setOrderGoodsOrderSub();
        $this->saveOrderGoods();
        return $this;
    }

    public function toApi()
    {
        $apiData = [
            'orderSn' => $this->getOrder()->order_sn,
            'user_id' => $this->getOrder()->user_id,
            'goods_num' => $this->getOrder()->goods_num,
        ];
        return $apiData;
    }

}